<template>
  <van-popup
    v-model:show="selfShow"
    position="bottom"
    :style="{ height: '30%' }"
    round
    class=""
  >
    <div class="main">
      <div class="tips">点击选择图片</div>
      <div class="photo-upload">
        <van-uploader
          v-model="fileList"
          max-count="1"
          :after-read="afterRead"
          :max-size="500 * 1024 * 1024 * 1024"
          @oversize="onOversize"
        />
      </div>
    </div>
  </van-popup>
</template>

<script setup lang="ts">
import { defineEmits, defineProps, ref } from 'vue'
import { useVModel } from '@vueuse/core'
import axios from '../../api/axios'
import { useStore } from '/@/store'
import { Toast } from 'vant'
import imageCompression from 'browser-image-compression'

const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
})

const emit = defineEmits(['update:show'])

const selfShow = useVModel(props, 'show', emit)

const { fileList, afterRead, onOversize } = usePhoto({ selfShow })

function usePhoto({ selfShow }: { selfShow: any }) {
  const fileList = ref<any[]>([])

  const { state } = useStore()

  return {
    fileList,
    async afterRead({ file }: any) {
      const options = {
        maxSizeMB: 0.5,
        // maxWidthOrHeight: 1920,
        useWebWorker: true,
      }
      try {
        const compressedFile = await imageCompression(file, options)
        console.log(
          'compressedFile instanceof Blob',
          compressedFile instanceof Blob
        ) // true
        console.log(
          `compressedFile size ${compressedFile.size / 1024 / 1024} MB`
        ) // smaller than maxSizeMB

        // 创建FormData对象
        let param = new FormData()
        // 将得到的文件流添加到FormData对象
        param.append('file', compressedFile, compressedFile.name)
        const {
          data: {
            data: { fileUrl },
          },
        } = await importFile(param)
        const userId = state.user.userId
        await addAppHeadUrl({ avatar: fileUrl, userId })
        selfShow.value = false
      } catch (error: any) {
        console.log(error)
        selfShow.value = false
        Toast(error)
      }
    },
    onOversize() {
      // Toast('文件大小不能超过 500kb')
      Toast('文件大小不能超过 50MB')
    },
  }
}

/* 上传文件 */
const importFile = (data: any) =>
  axios({
    url: '/api/blade-file/file/uploadFile',
    method: 'post',
    headers: { 'Content-Type': 'multipart/form-data' },
    data,
  })

function addAppHeadUrl(params: any) {
  return axios.post('/api/blade-user/addAppHeadUrl', params)
}
</script>

<style lang="less" scoped>
.photo-upload {
  display: flex;
  align-items: center;
  padding: 20px;
  justify-content: center;
  // height: 100%;
}

.main {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  height: 100%;
}

.tips {
  font-size: 14px;
  text-align: center;
  color: #646566;
}
</style>
